[[...path]].page.tsx 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. import React, { useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import {
  4. isClient, isIPageInfoForEntity, pagePathUtils, pathUtils,
  5. } from '@growi/core';
  6. import type {
  7. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, IUser, IUserHasId,
  8. } from '@growi/core';
  9. import ExtensibleCustomError from 'extensible-custom-error';
  10. import {
  11. NextPage, GetServerSideProps, GetServerSidePropsContext,
  12. } from 'next';
  13. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  14. import dynamic from 'next/dynamic';
  15. import Head from 'next/head';
  16. import { useRouter } from 'next/router';
  17. import superjson from 'superjson';
  18. import { Comments } from '~/components/Comments';
  19. import { PageAlerts } from '~/components/PageAlert/PageAlerts';
  20. // import { useTranslation } from '~/i18n';
  21. import { CurrentPageContentFooter } from '~/components/PageContentFooter';
  22. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  23. import { UsersHomePageFooterProps } from '~/components/UsersHomePageFooter';
  24. import type { CrowiRequest } from '~/interfaces/crowi-request';
  25. // import { renderScriptTagByName, renderHighlightJsStyleTag } from '~/service/cdn-resources-loader';
  26. // import { useRendererSettings } from '~/stores/renderer';
  27. // import { EditorMode, useEditorMode, useIsMobile } from '~/stores/ui';
  28. import type { EditorConfig } from '~/interfaces/editor-settings';
  29. import type { RendererConfig } from '~/interfaces/services/renderer';
  30. import type { ISidebarConfig } from '~/interfaces/sidebar-config';
  31. import type { IUserUISettings } from '~/interfaces/user-ui-settings';
  32. import type { PageModel, PageDocument } from '~/server/models/page';
  33. import type { PageRedirectModel } from '~/server/models/page-redirect';
  34. import type { UserUISettingsModel } from '~/server/models/user-ui-settings';
  35. import { useEditingMarkdown } from '~/stores/editor';
  36. import { useSWRxCurrentPage, useSWRxIsGrantNormalized } from '~/stores/page';
  37. import { useRedirectFrom } from '~/stores/page-redirect';
  38. import {
  39. useEditorMode, useSelectedGrant,
  40. usePreferDrawerModeByUser, usePreferDrawerModeOnEditByUser, useSidebarCollapsed, useCurrentSidebarContents, useCurrentProductNavWidth,
  41. } from '~/stores/ui';
  42. import loggerFactory from '~/utils/logger';
  43. // import { isUserPage, isTrashPage, isSharedPage } from '~/utils/path-utils';
  44. // import GrowiSubNavigation from '../client/js/components/Navbar/GrowiSubNavigation';
  45. // import GrowiSubNavigationSwitcher from '../client/js/components/Navbar/GrowiSubNavigationSwitcher';
  46. import { DescendantsPageListModal } from '../components/DescendantsPageListModal';
  47. import { BasicLayout } from '../components/Layout/BasicLayout';
  48. import GrowiContextualSubNavigation from '../components/Navbar/GrowiContextualSubNavigation';
  49. import DisplaySwitcher from '../components/Page/DisplaySwitcher';
  50. // import { serializeUserSecurely } from '../server/models/serializers/user-serializer';
  51. // import PageStatusAlert from '../client/js/components/PageStatusAlert';
  52. import {
  53. useCurrentUser,
  54. useIsLatestRevision,
  55. useIsForbidden, useIsNotFound, useIsSharedUser,
  56. useIsEnabledStaleNotification, useIsIdenticalPath,
  57. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  58. useDrawioUri, useHackmdUri, useDefaultIndentSize, useIsIndentSizeForced,
  59. useIsAclEnabled, useIsSearchPage, useTemplateTagData, useTemplateBodyData, useIsEnabledAttachTitleHeader,
  60. useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPageId, useCurrentPathname,
  61. useIsSlackConfigured, useRendererConfig,
  62. useEditorConfig, useIsAllReplyShown, useIsUploadableFile, useIsUploadableImage, useCustomizedLogoSrc, useIsContainerFluid,
  63. } from '../stores/context';
  64. import {
  65. CommonProps, getNextI18NextConfig, getServerSideCommonProps, useCustomTitle,
  66. } from './utils/commons';
  67. // import { useCurrentPageSWR } from '../stores/page';
  68. declare global {
  69. // eslint-disable-next-line vars-on-top, no-var
  70. var globalEmitter: EventEmitter;
  71. }
  72. const NotCreatablePage = dynamic(() => import('../components/NotCreatablePage').then(mod => mod.NotCreatablePage), { ssr: false });
  73. const ForbiddenPage = dynamic(() => import('../components/ForbiddenPage'), { ssr: false });
  74. const UnsavedAlertDialog = dynamic(() => import('../components/UnsavedAlertDialog'), { ssr: false });
  75. const GrowiSubNavigationSwitcher = dynamic(() => import('../components/Navbar/GrowiSubNavigationSwitcher'), { ssr: false });
  76. const UsersHomePageFooter = dynamic<UsersHomePageFooterProps>(() => import('../components/UsersHomePageFooter')
  77. .then(mod => mod.UsersHomePageFooter), { ssr: false });
  78. const DrawioModal = dynamic(() => import('../components/PageEditor/DrawioModal').then(mod => mod.DrawioModal), { ssr: false });
  79. const HandsontableModal = dynamic(() => import('../components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  80. const logger = loggerFactory('growi:pages:all');
  81. const {
  82. isPermalink: _isPermalink, isUsersHomePage, isTrashPage: _isTrashPage, isUserPage, isCreatablePage, isTopPage,
  83. } = pagePathUtils;
  84. const { removeHeadingSlash } = pathUtils;
  85. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  86. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  87. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  88. {
  89. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  90. return v?.data != null
  91. && v?.data.toObject != null
  92. && v?.meta != null
  93. && isIPageInfoForEntity(v.meta);
  94. },
  95. serialize: (v) => {
  96. return {
  97. data: superjson.stringify(v.data.toObject()),
  98. meta: superjson.stringify(v.meta),
  99. };
  100. },
  101. deserialize: (v) => {
  102. return {
  103. data: superjson.parse(v.data),
  104. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  105. };
  106. },
  107. },
  108. 'IPageToShowRevisionWithMetaTransformer',
  109. );
  110. const IdenticalPathPage = (): JSX.Element => {
  111. const IdenticalPathPage = dynamic(() => import('../components/IdenticalPathPage').then(mod => mod.IdenticalPathPage), { ssr: false });
  112. return <IdenticalPathPage />;
  113. };
  114. const PutbackPageModal = (): JSX.Element => {
  115. const PutbackPageModal = dynamic(() => import('../components/PutbackPageModal'), { ssr: false });
  116. return <PutbackPageModal />;
  117. };
  118. type Props = CommonProps & {
  119. currentUser: IUser,
  120. pageWithMeta: IPageToShowRevisionWithMeta | null,
  121. // pageUser?: any,
  122. redirectFrom?: string;
  123. // shareLinkId?: string;
  124. isLatestRevision?: boolean,
  125. isIdenticalPathPage?: boolean,
  126. isForbidden: boolean,
  127. isNotFound: boolean,
  128. isNotCreatablePage: boolean,
  129. // isAbleToDeleteCompletely: boolean,
  130. templateTagData?: string[],
  131. templateBodyData?: string,
  132. isSearchServiceConfigured: boolean,
  133. isSearchServiceReachable: boolean,
  134. isSearchScopeChildrenAsDefault: boolean,
  135. isSlackConfigured: boolean,
  136. // isMailerSetup: boolean,
  137. isAclEnabled: boolean,
  138. // hasSlackConfig: boolean,
  139. drawioUri: string | null,
  140. hackmdUri: string,
  141. noCdn: string,
  142. // highlightJsStyle: string,
  143. isAllReplyShown: boolean,
  144. isContainerFluid: boolean,
  145. editorConfig: EditorConfig,
  146. isEnabledStaleNotification: boolean,
  147. isEnabledAttachTitleHeader: boolean,
  148. // isEnabledLinebreaks: boolean,
  149. // isEnabledLinebreaksInComments: boolean,
  150. adminPreferredIndentSize: number,
  151. isIndentSizeForced: boolean,
  152. disableLinkSharing: boolean,
  153. rendererConfig: RendererConfig,
  154. // UI
  155. userUISettings?: IUserUISettings
  156. // Sidebar
  157. sidebarConfig: ISidebarConfig,
  158. };
  159. const GrowiPage: NextPage<Props> = (props: Props) => {
  160. // const { t } = useTranslation();
  161. const router = useRouter();
  162. const { data: currentUser } = useCurrentUser(props.currentUser ?? null);
  163. // register global EventEmitter
  164. if (isClient() && window.globalEmitter == null) {
  165. window.globalEmitter = new EventEmitter();
  166. }
  167. // commons
  168. useEditorConfig(props.editorConfig);
  169. useCsrfToken(props.csrfToken);
  170. useCustomizedLogoSrc(props.customizedLogoSrc);
  171. // UserUISettings
  172. usePreferDrawerModeByUser(props.userUISettings?.preferDrawerModeByUser ?? props.sidebarConfig.isSidebarDrawerMode);
  173. usePreferDrawerModeOnEditByUser(props.userUISettings?.preferDrawerModeOnEditByUser);
  174. useSidebarCollapsed(props.userUISettings?.isSidebarCollapsed ?? props.sidebarConfig.isSidebarClosedAtDockMode);
  175. useCurrentSidebarContents(props.userUISettings?.currentSidebarContents);
  176. useCurrentProductNavWidth(props.userUISettings?.currentProductNavWidth);
  177. // page
  178. useIsLatestRevision(props.isLatestRevision);
  179. useIsContainerFluid(props.isContainerFluid);
  180. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  181. useIsForbidden(props.isForbidden);
  182. useIsNotFound(props.isNotFound);
  183. // useIsNotCreatable(props.IsNotCreatable);
  184. useRedirectFrom(props.redirectFrom);
  185. // useShared();
  186. // useShareLinkId(props.shareLinkId);
  187. useIsSharedUser(false); // this page cann't be routed for '/share'
  188. useIsIdenticalPath(false); // TODO: need to initialize from props
  189. // useIsAbleToDeleteCompletely(props.isAbleToDeleteCompletely);
  190. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  191. useIsSearchPage(false);
  192. useTemplateTagData(props.templateTagData);
  193. useTemplateBodyData(props.templateBodyData);
  194. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  195. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  196. useIsSearchServiceReachable(props.isSearchServiceReachable);
  197. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  198. useIsSlackConfigured(props.isSlackConfigured);
  199. // useIsMailerSetup(props.isMailerSetup);
  200. useIsAclEnabled(props.isAclEnabled);
  201. // useHasSlackConfig(props.hasSlackConfig);
  202. useDrawioUri(props.drawioUri);
  203. useHackmdUri(props.hackmdUri);
  204. // useNoCdn(props.noCdn);
  205. useDefaultIndentSize(props.adminPreferredIndentSize);
  206. useIsIndentSizeForced(props.isIndentSizeForced);
  207. useDisableLinkSharing(props.disableLinkSharing);
  208. useRendererConfig(props.rendererConfig);
  209. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  210. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  211. useIsAllReplyShown(props.isAllReplyShown);
  212. useIsUploadableFile(props.editorConfig.upload.isUploadableFile);
  213. useIsUploadableImage(props.editorConfig.upload.isUploadableImage);
  214. const { pageWithMeta, userUISettings } = props;
  215. const pageId = pageWithMeta?.data._id;
  216. const pagePath = pageWithMeta?.data.path ?? (!_isPermalink(props.currentPathname) ? props.currentPathname : undefined);
  217. useCurrentPageId(pageId ?? null);
  218. // useIsNotCreatable(props.isForbidden || !isCreatablePage(pagePath)); // TODO: need to include props.isIdentical
  219. useCurrentPathname(props.currentPathname);
  220. const { data: currentPage } = useSWRxCurrentPage(undefined, pageWithMeta?.data ?? null); // store initial data
  221. useEditingMarkdown(pageWithMeta?.data.revision?.body);
  222. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  223. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  224. const { getClassNamesByEditorMode } = useEditorMode();
  225. const shouldRenderPutbackPageModal = pageWithMeta != null
  226. ? _isTrashPage(pageWithMeta.data.path)
  227. : false;
  228. // sync grant data
  229. useEffect(() => {
  230. mutateSelectedGrant(grantData?.grantData.currentPageGrant);
  231. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant]);
  232. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  233. useEffect(() => {
  234. const decodedURI = decodeURI(window.location.pathname);
  235. if (isClient() && decodedURI !== props.currentPathname) {
  236. router.replace(props.currentPathname, undefined, { shallow: true });
  237. }
  238. }, [props.currentPathname, router]);
  239. const classNames: string[] = [];
  240. const isSidebar = pagePath === '/Sidebar';
  241. classNames.push(...getClassNamesByEditorMode(isSidebar));
  242. const isTopPagePath = isTopPage(pageWithMeta?.data.path ?? '');
  243. const isContainerFluidEachPage = currentPage == null || !('expandContentWidth' in currentPage)
  244. ? null
  245. : currentPage.expandContentWidth;
  246. const isContainerFluidDefault = props.isContainerFluid;
  247. const isContainerFluid = isContainerFluidEachPage ?? isContainerFluidDefault;
  248. return (
  249. <>
  250. <Head>
  251. {/*
  252. {renderScriptTagByName('drawio-viewer')}
  253. {renderScriptTagByName('highlight-addons')}
  254. {renderHighlightJsStyleTag(props.highlightJsStyle)}
  255. */}
  256. </Head>
  257. <DrawioViewerScript />
  258. <BasicLayout title={useCustomTitle(props, 'GROWI')} className={classNames.join(' ')} expandContainer={isContainerFluid}>
  259. <div className="h-100 d-flex flex-column justify-content-between">
  260. <header className="py-0 position-relative">
  261. <div id="grw-subnav-container">
  262. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  263. </div>
  264. </header>
  265. <div className="d-edit-none">
  266. <GrowiSubNavigationSwitcher />
  267. </div>
  268. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  269. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  270. <div className="flex-grow-1">
  271. <div id="main" className={`main ${isUsersHomePage(props.currentPathname) && 'user-page'}`}>
  272. <div id="content-main" className="content-main grw-container-convertible">
  273. { props.isIdenticalPathPage && <IdenticalPathPage /> }
  274. { !props.isIdenticalPathPage && (
  275. <>
  276. <PageAlerts />
  277. { props.isForbidden && <ForbiddenPage /> }
  278. { props.isNotCreatablePage && <NotCreatablePage />}
  279. { !props.isForbidden && !props.isNotCreatablePage && <DisplaySwitcher />}
  280. {/* <DisplaySwitcher /> */}
  281. {/* <PageStatusAlert /> */}
  282. </>
  283. ) }
  284. {/* <div className="col-xl-2 col-lg-3 d-none d-lg-block revision-toc-container">
  285. <div id="revision-toc" className="revision-toc mt-3 sps sps--abv" data-sps-offset="123">
  286. <div id="revision-toc-content" className="revision-toc-content"></div>
  287. </div>
  288. </div> */}
  289. </div>
  290. </div>
  291. </div>
  292. { !props.isIdenticalPathPage && !props.isNotFound && (
  293. <footer className="footer d-edit-none">
  294. { pageWithMeta != null && pagePath != null && !isTopPagePath && (
  295. <Comments pageId={pageId} pagePath={pagePath} revision={pageWithMeta.data.revision} />
  296. ) }
  297. { pageWithMeta != null && isUsersHomePage(pageWithMeta.data.path) && (
  298. <UsersHomePageFooter creatorId={pageWithMeta.data.creator._id}/>
  299. ) }
  300. <CurrentPageContentFooter />
  301. </footer>
  302. )}
  303. <UnsavedAlertDialog />
  304. <DescendantsPageListModal />
  305. <DrawioModal />
  306. <HandsontableModal />
  307. {shouldRenderPutbackPageModal && <PutbackPageModal />}
  308. </div>
  309. </BasicLayout>
  310. </>
  311. );
  312. };
  313. function getPageIdFromPathname(currentPathname: string): string | null {
  314. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  315. }
  316. class MultiplePagesHitsError extends ExtensibleCustomError {
  317. pagePath: string;
  318. constructor(pagePath: string) {
  319. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  320. this.pagePath = pagePath;
  321. }
  322. }
  323. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  324. const { model: mongooseModel } = await import('mongoose');
  325. const req: CrowiRequest = context.req as CrowiRequest;
  326. const { crowi } = req;
  327. const { revisionId } = req.query;
  328. const Page = crowi.model('Page') as PageModel;
  329. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  330. const { pageService } = crowi;
  331. let currentPathname = props.currentPathname;
  332. const pageId = getPageIdFromPathname(currentPathname);
  333. const isPermalink = _isPermalink(currentPathname);
  334. const { user } = req;
  335. if (!isPermalink) {
  336. // check redirects
  337. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  338. if (chains != null) {
  339. // overwrite currentPathname
  340. currentPathname = chains.end.toPath;
  341. props.currentPathname = currentPathname;
  342. // set redirectFrom
  343. props.redirectFrom = chains.start.fromPath;
  344. }
  345. // check whether the specified page path hits to multiple pages
  346. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  347. if (count > 1) {
  348. throw new MultiplePagesHitsError(currentPathname);
  349. }
  350. }
  351. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  352. const page = pageWithMeta?.data as unknown as PageDocument;
  353. // add user to seen users
  354. if (page != null && user != null) {
  355. await page.seen(user);
  356. }
  357. // populate & check if the revision is latest
  358. if (page != null) {
  359. page.initLatestRevisionField(revisionId);
  360. await page.populateDataToShowRevision();
  361. props.isLatestRevision = page.isLatestRevision();
  362. }
  363. if (page == null && user != null) {
  364. const templateData = await Page.findTemplate(props.currentPathname);
  365. if (templateData != null) {
  366. props.templateTagData = templateData.templateTags as string[];
  367. props.templateBodyData = templateData.templateBody as string;
  368. }
  369. }
  370. props.pageWithMeta = pageWithMeta;
  371. }
  372. async function injectUserUISettings(context: GetServerSidePropsContext, props: Props): Promise<void> {
  373. const { model: mongooseModel } = await import('mongoose');
  374. const req = context.req as CrowiRequest<IUserHasId & any>;
  375. const { user } = req;
  376. const UserUISettings = mongooseModel('UserUISettings') as UserUISettingsModel;
  377. const userUISettings = user == null ? null : await UserUISettings.findOne({ user: user._id }).exec();
  378. if (userUISettings != null) {
  379. props.userUISettings = userUISettings.toObject();
  380. }
  381. }
  382. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  383. const req: CrowiRequest = context.req as CrowiRequest;
  384. const { crowi } = req;
  385. const Page = crowi.model('Page') as PageModel;
  386. const { currentPathname } = props;
  387. const pageId = getPageIdFromPathname(currentPathname);
  388. const isPermalink = _isPermalink(currentPathname);
  389. const page = props.pageWithMeta?.data;
  390. if (props.isIdenticalPathPage) {
  391. // TBD
  392. }
  393. else if (page == null) {
  394. props.isNotFound = true;
  395. props.isNotCreatablePage = !isCreatablePage(currentPathname);
  396. // check the page is forbidden or just does not exist.
  397. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  398. props.isForbidden = count > 0;
  399. }
  400. else {
  401. props.isNotFound = page.isEmpty;
  402. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  403. if (isPermalink && page.isEmpty) {
  404. props.currentPathname = page.path;
  405. }
  406. // /path/to/page ==> /62a88db47fed8b2d94f30000
  407. if (!isPermalink && !page.isEmpty) {
  408. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  409. if (!isToppage) {
  410. props.currentPathname = `/${page._id}`;
  411. }
  412. }
  413. }
  414. }
  415. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  416. // const req: CrowiRequest = context.req as CrowiRequest;
  417. // const { crowi } = req;
  418. // const UserModel = crowi.model('User');
  419. // if (isUserPage(props.currentPagePath)) {
  420. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  421. // if (user != null) {
  422. // props.pageUser = JSON.stringify(user.toObject());
  423. // }
  424. // }
  425. // }
  426. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  427. const req: CrowiRequest = context.req as CrowiRequest;
  428. const { crowi } = req;
  429. const {
  430. appService, searchService, configManager, aclService, slackNotificationService, mailService,
  431. } = crowi;
  432. props.isSearchServiceConfigured = searchService.isConfigured;
  433. props.isSearchServiceReachable = searchService.isReachable;
  434. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  435. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  436. // props.isMailerSetup = mailService.isMailerSetup;
  437. props.isAclEnabled = aclService.isAclEnabled();
  438. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  439. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  440. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  441. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  442. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  443. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  444. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  445. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  446. // props.isEnabledLinebreaks = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks');
  447. // props.isEnabledLinebreaksInComments = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments');
  448. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  449. props.editorConfig = {
  450. upload: {
  451. isUploadableFile: crowi.fileUploadService.getFileUploadEnabled(),
  452. isUploadableImage: crowi.fileUploadService.getIsUploadable(),
  453. },
  454. };
  455. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  456. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  457. props.isEnabledAttachTitleHeader = configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader');
  458. props.rendererConfig = {
  459. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  460. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  461. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  462. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  463. plantumlUri: process.env.PLANTUML_URI ?? null,
  464. blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
  465. // XSS Options
  466. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:xss:isEnabledPrevention'),
  467. attrWhiteList: crowi.xssService.getAttrWhiteList(),
  468. tagWhiteList: crowi.xssService.getTagWhiteList(),
  469. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  470. };
  471. props.sidebarConfig = {
  472. isSidebarDrawerMode: configManager.getConfig('crowi', 'customize:isSidebarDrawerMode'),
  473. isSidebarClosedAtDockMode: configManager.getConfig('crowi', 'customize:isSidebarClosedAtDockMode'),
  474. };
  475. }
  476. /**
  477. * for Server Side Translations
  478. * @param context
  479. * @param props
  480. * @param namespacesRequired
  481. */
  482. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  483. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  484. props._nextI18Next = nextI18NextConfig._nextI18Next;
  485. }
  486. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  487. const req = context.req as CrowiRequest<IUserHasId & any>;
  488. const { user } = req;
  489. const result = await getServerSideCommonProps(context);
  490. // check for presence
  491. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  492. if (!('props' in result)) {
  493. throw new Error('invalid getSSP result');
  494. }
  495. const props: Props = result.props as Props;
  496. if (props.redirectDestination != null) {
  497. return {
  498. redirect: {
  499. permanent: false,
  500. destination: props.redirectDestination,
  501. },
  502. };
  503. }
  504. if (user != null) {
  505. props.currentUser = user.toObject();
  506. }
  507. try {
  508. await injectPageData(context, props);
  509. }
  510. catch (err) {
  511. if (err instanceof MultiplePagesHitsError) {
  512. props.isIdenticalPathPage = true;
  513. }
  514. else {
  515. throw err;
  516. }
  517. }
  518. await injectUserUISettings(context, props);
  519. await injectRoutingInformation(context, props);
  520. injectServerConfigurations(context, props);
  521. await injectNextI18NextConfigurations(context, props, ['translation']);
  522. return {
  523. props,
  524. };
  525. };
  526. export default GrowiPage;